package com.lujieni.async.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
public class AsyncConfig {

    /**
     *
     * @Bean("taskExecutor")
     * 关键，只有叫taskExecutor才能代替默认的异步线程池的实现
     * @return
     */
    @Bean("taskExecutor")
    public Executor asyncExecutor() {
       return new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new CustomThreadFactory("lujieni"));
    }

    private static class CustomThreadFactory implements ThreadFactory {
        private final String namePrefix;

        public CustomThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(namePrefix + "-" + thread.getId());
            return thread;
        }
    }

}
